<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\DataCheck\Enums\RunModeEnum;
use Modules\DataCheck\Enums\TaskStateEnum;
use Modules\DataCheck\Models\DcTask;
use Modules\DataCheck\Services\DataCheckService;
use Symfony\Component\Console\Command\Command as CommandAlias;

class DataCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'data-check {taskId}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '数据核对';

    /**
     * Execute the console command.
     *
     * @param DataCheckService $service
     * @return int
     */
    public function handle(DataCheckService $service): int
    {
        $taskId = $this->argument('taskId');

        //获取任务
        $task = DcTask::query()->where('task_id', $taskId)->first();
        if (empty($task)) {
            $this->error('任务不存在');
            return CommandAlias::FAILURE;
        }

        //待执行、失败的任务才可执行
        if (!in_array($task->task_state, [TaskStateEnum::WAIT->value, TaskStateEnum::FAILED->value])) {
            $this->error('任务已执行，不可重新执行');
            return CommandAlias::FAILURE;
        }

        //更新任务状态为等待执行，后面有会状态校验
        DcTask::query()->where('task_id', $taskId)->update([
            'task_state' => TaskStateEnum::WAIT_RUNNING->value,
            'updated_at' => time(),
        ]);

        $service->handle($task, RunModeEnum::CONSOLE);
        return Command::SUCCESS;
    }
}
